package com.etalk.crm.controller;

import com.alibaba.fastjson.JSONObject;
import com.etalk.crm.pojo.KcPackage;
import com.etalk.crm.pojo.StudentDynamics;
import com.etalk.crm.pojo.StudentInfo;
import com.etalk.crm.service.KcPackageService;
import com.etalk.crm.service.PersonService;
import com.etalk.crm.service.StuDynamicService;
import com.etalk.crm.utils.OssGetObject;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.etalk.crm.controller.StudentDynamicCtl.DYNAMICS_ATTACHMENT_UPLOAD_PATH;

/**
 * @Auther: James
 * @Date: 2019/2/21 11:37
 * @Description: pcp 数据表
 */
@Controller
@RequestMapping(value = "/PcpCtl", produces = "application/json; charset=utf-8")
public class PcpController {
    private static final Logger logger = LogManager.getLogger(PcpController.class);

    @Resource
    private PersonService personService;

    @Resource
    KcPackageService kcPackageService;

    @Resource
    StuDynamicService stuDynamicService;

    /**
     * pcp 数据表
     *
     * @return
     */
    @RequestMapping(value = "/toPcp", method = RequestMethod.GET)
    public String toPcp(Integer personId, Model model) throws ParseException {
        //学员基本信息
        StudentInfo studentInfo = personService.pcpInfo(personId);
        model.addAttribute("studentInfo", studentInfo);

        model.addAttribute("listImg",personService.selectPcpRecordByPersonId(personId));
        // 学员星星数目
        Integer lessonStart = personService.selectLastLessonStar(personId);
        model.addAttribute("lessonStart", lessonStart);

        if (studentInfo.getReleaseTime() != null) {
            long diff = new Date().getTime() - studentInfo.getReleaseTime().getTime();
            int hours = (int) (diff / (1000 * 60 * 60));
            if (0 <= hours && hours <= 24) {
                model.addAttribute("scholarship", true);
            }
        }
        return "pcp/index";
    }

    @RequestMapping(value = "/savePcpInfo", method = RequestMethod.POST)
    @ResponseBody
    public String savePcpInfo(String pageData, Integer personId, String studentLogin, String learningDifficulty, Integer currentPcpDownloadCount, HttpSession session) {
        Map<String, Object> jsonMap = new HashMap();
        boolean flag = false;

        logger.debug("上传PDF到OSS，pageData=>" + pageData);
        String newName = studentLogin + "_" + personId + "_" + currentPcpDownloadCount + ".png";
        System.out.println("new file name==>" + newName);
        try {
            // 上传附件到oss
            OssGetObject.uploadPcpPdf(pageData, newName);
            String attachmentUrl = DYNAMICS_ATTACHMENT_UPLOAD_PATH + newName;

            // pcp学习计划动态模板
            String content = "【PCP计划表】生成学员学习计划表";

            StudentDynamics studentDynamics = new StudentDynamics();
            studentDynamics.setAddUser(session.getAttribute("loginname").toString());
            studentDynamics.setAddUserId(Integer.parseInt(session.getAttribute("userid").toString()));
            studentDynamics.setAddTime(new Date());
            studentDynamics.setPersonId(personId);
            studentDynamics.setStudentLogin(studentLogin);
            studentDynamics.setContent(StringEscapeUtils.unescapeHtml(content.replaceAll("\n", "<br/>")));
            studentDynamics.setQuestionnaireId(0);

            int num = stuDynamicService.addSimpleStudentDynamics(studentDynamics);
            if (num > 0) {
                // 保存附件信息
                List<String> attids = new ArrayList<>();
                attids.add("0");
                List<String> imgurls = new ArrayList<>();
                imgurls.add(attachmentUrl);
                stuDynamicService.insertInfoDynamicsAttachments(attids, imgurls, studentDynamics.getId());

                // 保存学员信息（学习困难和下载次数）
                personService.updatePcpInfo(personId, learningDifficulty);
                //保存pcp历史图片记录
                stuDynamicService.addStudentPcpRecord(personId,attachmentUrl,session.getAttribute("loginname").toString());
            }

            Map imgMap = new HashMap();
            imgMap.put("fileName", newName);
            imgMap.put("attachmentUrl", attachmentUrl);
            jsonMap.put("imgMap", imgMap);

            jsonMap.put("addTime", new Date());
            jsonMap.put("dynamicsId", studentDynamics.getId());
            jsonMap.put("addUserId", Integer.parseInt(session.getAttribute("userid").toString()));

            // 操作成功
            flag = true;
        } catch (Exception e) {
            jsonMap.put("msg", "上传失败");
        }

        if (flag) {
            jsonMap.put("code", 1);
        } else {
            jsonMap.put("code", 0);
        }
        return JSONObject.toJSONString(jsonMap);
    }

    /**
     * 查询 一级级 教材列表
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/getFirstLevelTextBookList", method = RequestMethod.POST)
    @ResponseBody
    public String getFirstLevelTextBookList() {
        List<KcPackage> firstLevelTextList = kcPackageService.selectFirstLevelTextList();
        Map<String, Object> jsonMap = new HashMap();
        jsonMap.put("firstLevelTextList", firstLevelTextList);
        jsonMap.put("code", 1);
        return JSONObject.toJSONString(jsonMap);
    }

    /**
     * 查询 二三级 教材列表
     *
     * @param parentId
     * @return
     */
    @RequestMapping(value = "/getTextBookList", method = RequestMethod.POST)
    @ResponseBody
    public String selectTrackRemindByBccId(int parentId, String keyword) {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("parentId", parentId);
        paramMap.put("search", keyword);
        List<KcPackage> textBookList = kcPackageService.selectChildLevelTextList(paramMap);
        Map<String, Object> jsonMap = new HashMap();
        jsonMap.put("textBookList", textBookList);
        jsonMap.put("code", 1);
        return JSONObject.toJSONString(jsonMap);
    }

    /**
     * 查询 教材列表
     *
     * @param parentId 教材 父级id
     * @return
     */
    @RequestMapping(value = "/getTeachingMaterialList", method = RequestMethod.POST)
    @ResponseBody
    public String getTeachingMaterialList(int parentId, String keyword) {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("parentId", parentId);
        paramMap.put("search", keyword);
        List<KcPackage> teachingMaterialList = kcPackageService.teachingMaterialList(paramMap);
        Map<String, Object> jsonMap = new HashMap();
        jsonMap.put("teachingMaterialList", teachingMaterialList);
        jsonMap.put("code", 1);
        return JSONObject.toJSONString(jsonMap);
    }

    /**
     * 查询 正常套餐列表
     */
    @RequestMapping(value = "/getPackageInfoList", method = RequestMethod.POST)
    @ResponseBody
    public String getPackageInfoList(String keyword) {
        //正常套餐列表
        List<KcPackage> packageInfoList = kcPackageService.selectEffectivePackage(keyword);

        Map<String, Object> jsonMap = new HashMap();
        jsonMap.put("packageInfoList", packageInfoList);
        jsonMap.put("code", 1);
        return JSONObject.toJSONString(jsonMap);
    }

}
